package com.example.goods_manage.controller;


import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.goods_manage.utils.AjaxResult;
import com.example.goods_manage.utils.cache.GuavaMap;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;


/**
 * 验证码
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    /**
     * 图片生成
     */
    @Autowired
    public Producer producer;

    @Autowired
    private GuavaMap<String,String> codeGuavaMap;

    @GetMapping("/captcha")
    public AjaxResult captcha() throws IOException {

        //随机生成的验证码字符
        String code = producer.createText();

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        String str = "data:image/jpeg;base64,";

        String base64Img = str + Base64.getEncoder().encodeToString(outputStream.toByteArray());

        String key = IdUtil.simpleUUID();
        codeGuavaMap.put(key, code);

        JSONObject result = new JSONObject();
        result.put("codeImg",base64Img);
        result.put("codeKey",key);
        result.put("code",code);
        return AjaxResult.success(result);
    }

}
